package com.example.common.network.interceptor;

import com.example.common.network.NetWorkConfig;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Desc： 网络重试拦截器
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2020/9/18 0018 14:46
 */
public class RetryIntercepter implements Interceptor {
    /**
     * 假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）
     */
    private int retryNum = 0;
    /**
     * 最大重试次数
     */
    public int maxRetry = NetWorkConfig.REQ_MAX_RETRY_NUM;

    public RetryIntercepter(int maxRetry) {
        this.maxRetry = maxRetry;
    }

    public RetryIntercepter() {
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        System.out.println("###RetryInterceptor.retryNum=" + retryNum);
        Response response = chain.proceed(request);
        while (!response.isSuccessful() && retryNum < maxRetry) {
            retryNum++;
            System.out.println("retryNum=" + retryNum);
            response.close();
            response = chain.proceed(request);
        }
        return response;
    }
}
